/*
 * @lc app=leetcode.cn id=86 lang=cpp
 *
 * [86] 分隔链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* small = new ListNode(0);
        ListNode* large = new ListNode(0);

        auto pSmall = small, pLarge = large;

        for (;head != nullptr; head = head->next) {
            if (head->val < x) {
                pSmall->next = head;
                pSmall = pSmall->next;
            }
            else {
                pLarge->next = head;
                pLarge = pLarge->next;
            }
        }

        pLarge->next = nullptr;
        pSmall->next = large->next;
        
        auto result = small->next;
        delete small;
        delete large;

        return result;
    }
};
// @lc code=end

